package com.yueqian.Utils;



import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(urlPatterns = "/Verification_code")
public class Verification_code extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //响应头意思是 不缓存
        resp.setHeader("pragma","no-cache");
        //响应头意思是 缓存
        resp.setHeader("Cache-Control","no-cache");
        //响应头意思是 缓存时间
        resp.setDateHeader("Expires",0);
        int width=120;
        int height=40;
        BufferedImage  image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.GRAY);
        g.fillRect(0, 0, width, height);
        String checkCode = getCheckCode();
        req.getSession().setAttribute("CHECKCODE",checkCode);
         g.setColor(Color.BLUE);
         g.setFont(new Font("黑体",Font.BOLD,24));
         g.drawString(checkCode, 15, 25);
         ImageIO.write(image,"PNG",resp.getOutputStream());

    }

    //产生四位随机字符
    private String getCheckCode(){
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {
            int index = random.nextInt(size);
            sb.append(base.charAt(index));
        }
        return sb.toString();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello");
    }
}
